//
//  HomeViewModel.swift
//  FreeWallpaperSwiftUI
//
//  Created by 张少康 on 2023/11/28.
//

import Foundation
import Alamofire
import UIKit

class HomeViewModel: ObservableObject {
    
    let locationStr = ["zh-CN","en-US","ja-JP","de-DE","en-CA","en-GB","en-IN","fr-FR","it-IT"]
    
    @Published var wallpaperItems: [WallpaperItemModel] = []
    
    @Published var scrollToTop: Bool = false
    
    var allItems: [WallpaperItemModel] = []
    
    init() {
        fetchData()
    }
    
    func changeItems() {
        scrollToTop = true
        let array = (0..<10).compactMap { _ in
            self.allItems.randomElement()
        }
        self.wallpaperItems = array
    }
    
    func fetchData() {
        let loaction = locationStr.randomElement()
        let url = "https://raw.onmicrosoft.cn/Bing-Wallpaper-Action/main/data/\(loaction ?? "zh-CN" )_all.json"
        AF.request(url).responseJSON { response in
            switch response.result {
            case .success(let value):
                if let dic = value as? [String: Any], let dataDic = dic["data"] as? [Any] {
                    do {
                        print("返回的参数为 \(value)")
                        let jsonData = try JSONSerialization.data(withJSONObject: dataDic)
                        let decoder = JSONDecoder()
                        let result = try decoder.decode([WallpaperItemModel].self, from: jsonData)
                        self.allItems = result
                        self.changeItems()
                    } catch {
                        print("Error decoding JSON: \(error)")
                    }
                }else {
                    print("Error decoding JSON")
                }
                
            case .failure(let error):
                print("Network request failed with error: \(error)")
            }
        }
    }

}
